<script setup>
import { ref, onMounted, watch } from 'vue'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import { FullScreen, MousePosition, ScaleLine, ZoomSlider } from 'ol/control'
import ZoomToExtent from 'ol/control/ZoomToExtent'
import Map from 'ol/Map'
import 'ol/ol.css'
import axios from 'axios'
import { debounce } from 'lodash'
import { Vector } from 'ol/layer'
import VectorSource from 'ol/source/Vector'
import { GeoJSON } from 'ol/format'
import { Fill, Stroke, Style, Circle } from 'ol/style'
import VectorLayer from 'ol/layer/Vector'
import Draw from 'ol/interaction/Draw'
import { defaults as defaultInteractions } from 'ol/interaction'

const mapRef = ref(null)
const mapInstance = ref(null)
const popup = ref(null)
const beijingCenter = [116.4074, 39.9042]
const initialView = ref(
  new View({
    center: beijingCenter,
    zoom: 10,
    projection: 'EPSG:4326',
  }),
)

// 使用 ref 存储 cityLayer
const cityLayer = ref(null)
// 使用 ref 存储 draw 交互
const drawInteraction = ref(null)

const ip = async () => {
  try {
    const res = await axios({
      method: 'GET',
      url: "https://restapi.amap.com/v3/ip",
      params: {
        key: '38223f069a28ddf08d6ddd946e1cc338',
        ip: '123.149.204.236'
      }
    })
    console.log(res.data)
    adcode.value = res.data.adcode
    yourCity.value = res.data.city
    await address()
  } catch (error) {
    console.error('IP定位失败', error)
  }
}

const address = async () => {
  try {
    if (!yourCity.value) return

    const res2 = await axios({
      method: 'GET',
      url: 'https://restapi.amap.com/v3/geocode/geo',
      params: {
        key: '38223f069a28ddf08d6ddd946e1cc338',
        address: yourCity.value
      }
    })

    console.log(res2.data)

    // 检查是否有结果
    if (res2.data.geocodes?.length > 0) {
      adcode.value = res2.data.geocodes[0].adcode
      yourLocation.value = res2.data.geocodes[0].location.split(',').map(item => Number(item))

      // 删除旧图层
      if (cityLayer.value) {
        mapInstance.value.removeLayer(cityLayer.value)
        cityLayer.value = null
      }

      // 创建新图层
      cityLayer.value = new Vector({
        source: new VectorSource({
          url: `https://geo.datav.aliyun.com/areas_v3/bound/${adcode.value}.json`,
          format: new GeoJSON(),
        }),
        style: new Style({
          fill: new Fill({
            color: 'rgba(0, 0, 0, 0.5)',
          }),
          stroke: new Stroke({
            color: 'black'
          })
        })
      })

      mapInstance.value.addLayer(cityLayer.value)
      mapInstance.value.getView().animate({
        center: yourLocation.value,
        zoom: 10,
        duration: 2000
      })
    } else {
      console.error('未找到地理编码结果')
    }
  } catch (error) {
    console.error('获取地理编码失败:', error)
  }
}

const search = debounce((e) => {
  console.log('search', e.target.value)
  yourCity.value = e.target.value
  address()
}, 500)

const adcode = ref(null)
const input1 = ref(null)
const input2 = ref(null)
const input3 = ref(null)
const yourCity = ref('')
const yourLocation = ref(null)

const options1 = [
  {
    value: 'false',
    label: '关闭绘图',
  },
  {
    value: 'LineString', // OpenLayers 识别的线类型
    label: '线',
  },
  {
    value: 'Polygon', // OpenLayers 识别的多边形类型
    label: '多边形',
  },
  {
    value: 'Circle', // OpenLayers 识别的圆类型
    label: '圆',
  },
  {
    value: 'Point', // 可以添加点类型
    label: '点',
  },
  {
    value: 'clear',
    label: '清除所有绘图'
  }
]
const options2 = [
  {
    value: 'false',
    label: 'false',
  },
  {
    value: 'charging-station',
    label: '充电桩',
  },
  {
    value: 'bus-station',
    label: '公交站',
  },
  {
    value: 'parking',
    label: '停车场',
  },
]
const drawLayer = ref(new VectorLayer({
  source: new VectorSource(),
  style: new Style({
    fill: new Fill({
      color: 'rgba(255, 0, 0, 0.5)',
    }),
    stroke: new Stroke({
      color: 'black',
      width: 2,
    }),
    image: new Circle({
      radius: 7,
      fill: new Fill({
        color: 'rgba(0, 0, 255, 0.5)'
      }),
      stroke: new Stroke({
        color: 'blue',
        width: 2
      })
    })
  })
}))

const drawType = ref(null)
const gaodeLayer = new TileLayer({
  source: new XYZ({
    url: 'https://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
    crossOrigin: 'anonymous',
  }),
})

onMounted(async () => {
  mapInstance.value = new Map({
    target: mapRef.value,
    view: initialView.value,
    layers: [gaodeLayer, drawLayer.value],
    controls: [
      new ScaleLine(),
      new FullScreen(),
      new ZoomSlider(),
      new ZoomToExtent({
        extent: [115.7, 39.4, 117.4, 41.6],
      }),
      new MousePosition(),
    ],
    interactions: defaultInteractions() // 添加默认交互（拖拽、缩放等）
  })
  await ip()
  mapInstance.value.getView().on('change:resolution', function() {
    let zoom = this.getZoom()
    console.log(zoom)
    if (zoom>10) {
      drawLayer.value.setVisible(false)
      cityLayer.value.setVisible(false)
    } else {
      drawLayer.value.setVisible(true)
      cityLayer.value.setVisible(true)
    }
  })
})

// 修复绘图功能
watch(input2, (newValue) => {
  // 首先移除现有的绘图交互
  if (drawInteraction.value) {
    mapInstance.value.removeInteraction(drawInteraction.value)
    drawInteraction.value = null
  }

  // 处理清除操作
  if (newValue === 'clear') {
    drawLayer.value.getSource().clear()
    return
  }

  // 处理绘图类型切换
  if (newValue !== 'false' && newValue !== 'clear') {
    // 创建新的绘图交互
    drawInteraction.value = new Draw({
      source: drawLayer.value.getSource(),
      type: newValue,
    })

    // 添加到地图
    mapInstance.value.addInteraction(drawInteraction.value)

    // 监听绘图完成事件
    drawInteraction.value.on('drawend', (event) => {
      console.log('绘制完成', event.feature)
      // 可以根据需要保存绘制的图形
    })
  }
})
</script>

<template>
  <div id="map-container">
    <div id="nav">
      <p>{{ yourCity }}</p>
      <el-input
        v-model="yourCity"
        style="width: 200px"
        placeholder="请输入城市名称..."
        @keyup.enter="search"
      />
      <el-select v-model="input2" placeholder="画图" style="width: 240px">
        <el-option
          v-for="item in options1"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <div id="map" ref="mapRef"></div>
    <div id="popup"></div>
  </div>
</template>

<style scoped>
#map-container {
  width: 100vw;
  height: 100vh;
  position: relative;
}

#nav {
  height: 10vh;
  width: 100vw;
  background-color: lightgray;
  display: flex;
  align-items: center;
  justify-content: space-around;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

#map {
  height: 100vh;
  width: 100vw;
  position: absolute;
  top: 0;
  left: 0;
}
#popup{
  width:200px;
  height: max-content;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.23);
  z-index: 999;
}
</style>
